package keter.model;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.ext.plugin.tablebind.TableBind;
import com.jfinal.plugin.activerecord.Db;

import keter.framework.model.base.BaseModel;
import keter.framework.util.ModelUtil;

/**
 * 菜单
 * @author shadowedge
 *
 */
@TableBind(tableName="org_menu")
public class Menu extends BaseModel<Menu>{
	/**
	* Logger for this class
	*/
	private static final Logger logger = LoggerFactory.getLogger(Menu.class);
	
	public static final Menu dao = new Menu();
	
   public List<Menu> findAll(){
        return find(
        	" select m.id,m.label,m.url,m.icon,m.isleaf,m.parent_id,m.root_id "
          + " from org_menu m");
    }
	
    public  boolean save() {
    	this.set("isleaf", "true");
        return super.save();
    }
    
    public  boolean update() {
    	return super.update();
    }
    
	 
    public  int deleteByRootId(String rootId) {
    	//删除全部子菜单(包括自己)
    	return Db.update("delete from org_menu where root_id=?",wrap(rootId));
    }
    
	public List<Menu> findByParentId(Object pid) {
    	return find(
    		" select m.id,m.label,m.url,m.icon,m.isleaf,m.root_id "
    	   +" from org_menu m where m.parent_id=?",
    		wrap(pid)
    	);
	}
	
	public List<Menu> findByRoleList(List<Role> roleList) {
		String roleNames = ModelUtil.extractListToSqlIn(roleList, "name");
//		logger.info(roleNames);
		return find(
			" select m.id,m.label,m.url,m.icon,m.isleaf,m.parent_id,m.root_id "
		  + " from org_menu m where m.role_name in ("+roleNames+") "
	    );
	}
	   
	@Override
	protected void validate() {
		validator()
		.notEmpty("url")
		.notEmpty("label");	
	}

}
